<template>
  <div class="department-manage">
    <!-- 顶栏 -->
    <TopBar />

    <!-- 内容区域 -->
    <div class="content">
      <!-- 菜单 -->
      <MenuLine />

      <!-- 操作栏 -->
      <div class="operation-bar">
        <el-button type="primary" @click="openAddDialog">添加部门</el-button>
      </div>

      <!-- 部门列表 -->
      <el-table :data="departmentList" style="width: 100%" border>
        <el-table-column prop="id" label="ID" width="100" />
        <el-table-column prop="name" label="部门名称" width="200" />
        <el-table-column prop="description" label="部门描述" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" width="250" />
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="openEditDialog(row)">编辑</el-button>
            <el-button type="danger" size="small" @click="deleteDepartment(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加/编辑弹窗 -->
      <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="30%"
        @close="resetForm"
      >
        <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
          <el-form-item
            v-for="field in departmentFields"
            :key="field.key"
            :label="field.label"
            :prop="field.key"
          >
            <el-input
              v-if="field.type === 'text'"
              v-model="form[field.key]"
              :placeholder="field.placeholder"
              :maxlength="field.maxLength"
            />
            <el-input
              v-else-if="field.type === 'textarea'"
              v-model="form[field.key]"
              type="textarea"
              :rows="4"
              :placeholder="field.placeholder"
              :maxlength="field.maxLength"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus';
import { useDepartmentStore, departmentFields, type Department } from '@/stores/department';
import TopBar from '@/components/TopBar.vue';
import MenuLine from '@/components/MenuLine.vue';

// 部门 store
const departmentStore = useDepartmentStore();
const departmentList = ref(departmentStore.departments);

// 弹窗控制
const dialogVisible = ref(false);
const dialogTitle = ref('添加部门');
const isEdit = ref(false);
const form = ref<Department>({
  id: 0,
  name: '',
  description: '',
  createTime: '',
});
const formRef = ref<FormInstance>();

// 表单校验规则
const rules = ref<FormRules>({
  name: [
    { required: true, message: '请输入部门名称', trigger: 'blur' },
    { min: 1, max: 50, message: '部门名称长度在 1 到 50 字符', trigger: 'blur' },
  ],
  description: [
    { required: true, message: '请输入部门描述', trigger: 'blur' },
    { min: 1, max: 500, message: '部门描述长度在 1 到 500 字符', trigger: 'blur' },
  ],
});

// 获取部门列表
const fetchDepartments = async () => {
  try {
    const result = await departmentStore.fetchDepartments();
    departmentList.value = result;
  } catch (error) {
    ElMessage.error('获取部门列表失败');
  }
};

// 打开添加弹窗
const openAddDialog = () => {
  isEdit.value = false;
  dialogTitle.value = '添加部门';
  dialogVisible.value = true;
};

// 打开编辑弹窗
const openEditDialog = (row: Department) => {
  isEdit.value = true;
  dialogTitle.value = '编辑部门';
  form.value = { ...row };
  dialogVisible.value = true;
};

// 提交表单（添加或编辑）
const submitForm = async () => {
  if (!formRef.value) return;
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (isEdit.value) {
          await departmentStore.updateDepartment(form.value);
          ElMessage.success('编辑部门成功');
        } else {
          await departmentStore.createDepartment({
            name: form.value.name,
            description: form.value.description,
          });
          ElMessage.success('添加部门成功');
        }
        dialogVisible.value = false;
        fetchDepartments();
      } catch (error) {
        ElMessage.error(isEdit.value ? '编辑部门失败' : '添加部门失败');
      }
    }
  });
};

// 删除部门
const deleteDepartment = async (id: number) => {
  ElMessageBox.confirm('确定删除该部门吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        await departmentStore.deleteDepartment(id);
        ElMessage.success('删除部门成功');
        fetchDepartments();
      } catch (error) {
        ElMessage.error('删除部门失败');
      }
    })
    .catch(() => {
      ElMessage.info('取消删除');
    });
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  form.value = { id: 0, name: '', description: '' };
};

// 初始化加载
onMounted(() => {
  fetchDepartments();
});
</script>

<style scoped>
.department-manage {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.content {
  padding-top: 60px; /* 留出顶栏高度 */
  width: 80%;
  margin: 0 auto;
  padding-bottom: 60px; /* 底部留白 */
}

.operation-bar {
  margin: 20px 0;
}

.el-table {
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
</style>